package com.situ.object.controll;

import com.situ.object.entity.User;
import com.situ.object.service.UserService;
import com.situ.object.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    //合成类
    private  UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //一般直接调用get
        doGet(request,response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1、设置req编码格式和设置内容类型
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //第一步 获取参数 —— 在登录时从客户端（浏览器）获取用户输入的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //验证码
        String vercode = request.getParameter("vercode");
        String code = (String) request.getSession().getAttribute("code");

        if (!code.equalsIgnoreCase(vercode)){
            request.setAttribute("msg","验证码输入错误");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }

//        创建一个user对象
        User user = new User();
//        //使用user对象存储参数
        user.setUsername(username);
        user.setPassword(password);

        //会话保持，在会话保持期间，数据将一直保存在session中
        HttpSession session = request.getSession();

        try {
            //登录成功
            //登录成功后将登录成功的user返回
            user = userService.login(user);
            //设置Session
            session.setAttribute("user",user);
            //重定向
            response.sendRedirect("/");
        } catch (Exception e) {
            //打印错误信息
            System.out.println(e.getMessage());
            //四大作用域——request
            request.setAttribute("msg",e.getMessage());
            //转发
            request.getRequestDispatcher("/login.jsp").forward(request,response);

        }
    }
}
